package org.example.hadoop.service.authorRatingScore;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/**
 * @author wwy
 * @date 2020-11-10 19:39
 */
public class AuthorRatingScoreReducer extends Reducer<Text, Text, Text, Text> {
    /**
     * k2        v2
     * 余华       9.4,9.5
     *
     * k3        v3
     * 余华      (9.4+9.5)/2
     * @param key
     * @param values
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
        double ratingScoreDoubleNum = 0;
        double count = 0;
        for (Text value : values) {
            double ratingScoreDouble = 0;
            try {
                ratingScoreDouble = Double.parseDouble(value.toString());
                ratingScoreDoubleNum += ratingScoreDouble;
                count ++;
            } catch (NumberFormatException e) {

            }

        }
        double avg = ratingScoreDoubleNum/count;
        if(Double.isNaN(avg)){
            return;
        }

        context.write(key,new Text(String.valueOf(avg).substring(0,3)));
    }
}
